import { Hono } from 'hono'
import { checkDatabaseConnection } from '@/lib/database'
import { checkRedisConnection } from '@/lib/redis'
import { config } from '@/config/env'

const health = new Hono()

// 基础健康检查
health.get('/', async (c) => {
  const timestamp = new Date().toISOString()
  
  return c.json({
    status: 'healthy',
    timestamp,
    version: '0.1.0',
    environment: config.nodeEnv,
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    pid: process.pid
  })
})

// 详细健康检查
health.get('/detailed', async (c) => {
  const timestamp = new Date().toISOString()
  const startTime = Date.now()

  // 检查各个服务的健康状态
  const checks = await Promise.allSettled([
    checkDatabaseConnection(),
    checkRedisConnection(),
  ])

  const [dbCheck, redisCheck] = checks

  const services = {
    database: {
      status: dbCheck.status === 'fulfilled' && dbCheck.value ? 'healthy' : 'unhealthy',
      responseTime: Date.now() - startTime
    },
    redis: {
      status: redisCheck.status === 'fulfilled' && redisCheck.value ? 'healthy' : 'unhealthy',
      responseTime: Date.now() - startTime
    }
  }

  const allHealthy = Object.values(services).every(service => service.status === 'healthy')
  const overallStatus = allHealthy ? 'healthy' : 'degraded'

  const response = {
    status: overallStatus,
    timestamp,
    version: '0.1.0',
    environment: config.nodeEnv,
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    pid: process.pid,
    services
  }

  return c.json(response, allHealthy ? 200 : 503)
})

// 就绪检查 (Kubernetes readiness probe)
health.get('/ready', async (c) => {
  try {
    const dbHealthy = await checkDatabaseConnection()
    const redisHealthy = await checkRedisConnection()

    if (dbHealthy && redisHealthy) {
      return c.json({ status: 'ready' })
    } else {
      return c.json({ status: 'not ready' }, 503)
    }
  } catch (error) {
    return c.json({ status: 'not ready', error: 'Health check failed' }, 503)
  }
})

// 存活检查 (Kubernetes liveness probe)
health.get('/live', async (c) => {
  return c.json({ status: 'alive' })
})

// Prometheus 监控指标
health.get('/metrics', async (c) => {
  const metrics = [
    '# HELP bai_hu_api_uptime_seconds Total uptime of the API server',
    '# TYPE bai_hu_api_uptime_seconds counter',
    `bai_hu_api_uptime_seconds ${process.uptime()}`,
    '',
    '# HELP bai_hu_api_memory_usage_bytes Memory usage of the API server',
    '# TYPE bai_hu_api_memory_usage_bytes gauge',
    `bai_hu_api_memory_usage_bytes{type="rss"} ${process.memoryUsage().rss}`,
    `bai_hu_api_memory_usage_bytes{type="heapTotal"} ${process.memoryUsage().heapTotal}`,
    `bai_hu_api_memory_usage_bytes{type="heapUsed"} ${process.memoryUsage().heapUsed}`,
    `bai_hu_api_memory_usage_bytes{type="external"} ${process.memoryUsage().external}`,
    '',
    '# HELP bai_hu_api_process_id Process ID of the API server',
    '# TYPE bai_hu_api_process_id gauge',
    `bai_hu_api_process_id ${process.pid}`,
    ''
  ].join('\n')

  c.header('Content-Type', 'text/plain; version=0.0.4; charset=utf-8')
  return c.text(metrics)
})

export default health
